﻿using CefSharp;
using CefSharp.WinForms;
using kis.api.model;
using kis.UC;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace kis
{
    /// <summary>
    /// 
    /// </summary>
    public partial class Frm_Main : BaseForm
    {
        /// <summary>
        /// 
        /// </summary>
        public Dictionary<string, ChromiumWebBrowser> chromes { get; set; } = new Dictionary<string, ChromiumWebBrowser>();

        // <summary>
        /// 
        /// </summary>
        public ChromiumWebBrowser chromBrowser { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public Frm_Main()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected override void Form_KeyDown(object sender, KeyEventArgs e)
        {
            base.Form_KeyDown(sender, e);

            switch (e.KeyCode)
            {
                case Keys.F1:
                    KisUrlAdd();

                    break;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public override void Form_Closing(object sender, FormClosingEventArgs e)
        {
            base.Form_Closing(sender, e);

            if (!ShowAskDialog("您真的要退出系统吗？"))
            {
                e.Cancel = true;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public override void InitForm()
        {
            base.InitForm();

            InitDB();

            InitDataGridView(this.uiDG_list);

            this.uiDG_list.CellContentClick += UiDG_list_CellContentClick;

            Task.Run(() =>
            {
                GetJPM("");
            });
        }

        /// <summary>
        /// 
        /// </summary>
        public void InitializeChromium()
        {
            try
            {
                CefSettings settings = new CefSettings();

                settings.Locale = "zh-CN";
                settings.CachePath = AppDomain.CurrentDomain.BaseDirectory + "cache";
                settings.CefCommandLineArgs.Add("disable-application-cache", "0");
                settings.CefCommandLineArgs.Add("disable-session-storage", "0");

                settings.CefCommandLineArgs.Add("disable-gpu", "0");//去掉gpu，否则chrome显示有问题
                settings.CefCommandLineArgs.Add("ignore-certificate-errors");
                settings.CefCommandLineArgs.Add("enable-media-stream", "1");

                Cef.Initialize(settings);
                Cef.GetGlobalCookieManager();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void UiDG_list_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            dgCellContentAction(sender, e, (DataGridView dg, KisUrl item, string name) =>
            {
                switch (name)
                {
                    case "btn_Details":
                        ShowWindow(this, new Frm_UrlUpdate(item.id));

                        Frm_QueryData();

                        break;
                }
            });
        }

        /// <summary>
        /// 
        /// </summary>
        protected override void QueryData()
        {
            base.QueryData();

            var name = this.uiTBox_name.Text.Trim();
            var url = this.uiTBox_url.Text.Trim();

            var items = api.KisUrlGetList(name, url);

            SetDGColumnAttr(this.uiDG_list, items, ColumnAttrs());

            ToMenu();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override List<ColumnAttr> ColumnAttrs()
        {
            var list = new List<ColumnAttr>();

            list.Add(new ColumnAttr("btn_Details", "…", 45, ColumnType.Button));
            list.Add(new ColumnAttr("id", "编号", 85, DataGridViewContentAlignment.MiddleCenter, false));
            list.Add(new ColumnAttr("serial", "序号", 65, DataGridViewContentAlignment.MiddleCenter, true));
            list.Add(new ColumnAttr("name", "名称", 250, DataGridViewContentAlignment.MiddleLeft, true));
            list.Add(new ColumnAttr("jpm", "简拼码", 200, DataGridViewContentAlignment.MiddleCenter, true));
            list.Add(new ColumnAttr("url", "链接地址", 500, DataGridViewContentAlignment.MiddleLeft, true));

            return list;
        }

        /// <summary>
        /// 
        /// </summary>
        private void KisUrlAdd()
        {
            ShowWindow(this, new Frm_UrlUpdate());

            Frm_QueryData();
        }

        /// <summary>
        /// 
        /// </summary>
        public void ToMenu()
        {
            try
            {
                this.chromes.Clear();

                this.chromes = new Dictionary<string, ChromiumWebBrowser>();

                var items = api.KisUrlGetList();

                var tab = this.uiTabControl_Main;

                foreach (TabPage page in tab.TabPages)
                {
                    if (page.Name == "tPge_index")
                    {
                        continue;
                    }

                    tab.TabPages.Remove(page);
                }

                foreach (var item in items)
                {
                    var newPage = new TabPage();

                    newPage.Name = item.id.ToString();
                    newPage.Text = item.name;

                    if (!Cef.IsInitialized)
                    {
                        InitializeChromium();
                    }

                    var chromBrowser = new ChromiumWebBrowser(item.url);

                    BrowserSettings browserSettings = new BrowserSettings();

                    browserSettings.FileAccessFromFileUrls = CefState.Enabled;
                    browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;

                    chromBrowser.BrowserSettings = browserSettings;

                    newPage.Controls.Add(chromBrowser);

                    chromBrowser.Dock = DockStyle.Fill;

                    tab.TabPages.Add(newPage);

                    this.chromes.Add(item.name, chromBrowser);
                }
            }
            catch (Exception ex)
            {
                ShowErrorInfo("生成菜单发生error：" + ex.Message);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTBox_name_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiTBox_url_TextChanged(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_toMenu_Click(object sender, EventArgs e)
        {
            ToMenu();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void uiBtn_Add_Click(object sender, EventArgs e)
        {
            KisUrlAdd();
        }

        /// <summary>
        /// 调试
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlbl_debug_Click(object sender, EventArgs e)
        {
            try
            {
                var name = this.uiTabControl_Main.SelectedTab.Text;

                if (!this.chromes.ContainsKey(name))
                {
                    return;
                }

                var chrome = this.chromes[name];

                chrome.ShowDevTools();
            }
            catch (Exception ex)
            {
                ShowErrorInfo("打开调试代码error:" + ex.Message);
            }
        }
    }
}